package com.yz.fanrenmianshi.job.once;

import cn.hutool.core.collection.CollUtil;
import com.yz.fanrenmianshi.annotation.DistributedLock;
import com.yz.fanrenmianshi.esdao.QuestionEsDao;
import com.yz.fanrenmianshi.model.dto.question.QuestionEsDTO;
import com.yz.fanrenmianshi.model.entity.Question;
import com.yz.fanrenmianshi.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全量同步题目到 es
 */
// todo 取消注释开启任务
//@Component
@Slf4j
public class FullSyncQuestionToEs implements CommandLineRunner {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionEsDao questionEsDao;

    @Override
    public void run(String... args) {
        // 全量获取题目（数据量不大的情况下使用）
        List<Question> questionList = questionService.list();
        if (CollUtil.isEmpty(questionList)) {
            return;
        }
        // 过滤已删除的题目，只同步未删除的题目
        List<Question> activeQuestions = questionList.stream()
                .filter(question -> question.getIsDelete() == 0)
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(activeQuestions)) {
            log.info("No active questions to sync");
            return;
        }
        // 转为 ES 实体类
        List<QuestionEsDTO> questionEsDTOList = activeQuestions.stream()
                .map(QuestionEsDTO::objToDto)
                .collect(Collectors.toList());
        // 分页批量插入到 ES
        int total = questionEsDTOList.size();
        log.info("FullSyncQuestionToEs start, total {}", total);
        int pageSize = 100; // 减少每次批量写入的数据量
        for (int i = 0; i < total; i += pageSize) {
            // 注意同步的数据下标不能超过总数据量
            int end = Math.min(i + pageSize, total);
            log.info("sync from {} to {}", i, end);
            boolean success = false;
            int retryCount = 0;
            while (!success && retryCount < 3) { // 最多重试 3 次
                try {
                    questionEsDao.saveAll(questionEsDTOList.subList(i, end));
                    success = true;
                } catch (Exception e) {
                    retryCount++;
                    log.warn("Failed to sync data from {} to {}, retrying... ({})", i, end, retryCount, e);
                    try {
                        Thread.sleep(1000 * retryCount); // 等待一段时间再重试
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException("Interrupted during retry", ie);
                    }
                }
            }
            if (!success) {
                log.error("Failed to sync data from {} to {} after {} retries", i, end, retryCount);
            }
        }
        log.info("FullSyncQuestionToEs end, total {}", total);
    }
}
